package com.bytecamp.testplatform.util;

import com.bytecamp.testplatform.model.ApiInfo;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.PathItem;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.parameters.Parameter;
import io.swagger.v3.parser.OpenAPIV3Parser;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class OpenApiParserUtil {
    /**
     * 解析整个OpenAPI文档，提取所有接口的元数据
     */
    public static List<ApiInfo> parseAllApis(String yamlFilePath) {
        List<ApiInfo> apiInfoList = new ArrayList<>();
        try {
            // 1. 解析整个文档
            OpenAPIV3Parser parser = new OpenAPIV3Parser();
            OpenAPI openAPI = parser.read(yamlFilePath);
            if (openAPI == null || openAPI.getPaths() == null) {
                return apiInfoList;
            }

            // 2. 遍历所有路径（接口）
            Map<String, PathItem> paths = openAPI.getPaths();
            for (Map.Entry<String, PathItem> entry : paths.entrySet()) {
                String path = entry.getKey();
                PathItem pathItem = entry.getValue();

                // 3. 遍历路径下的所有HTTP方法（GET/POST等）
                if (pathItem.getGet() != null) {
                    apiInfoList.add(buildApiInfo(path, "GET", pathItem.getGet(), openAPI.getInfo().getTitle()));
                }
                if (pathItem.getPost() != null) {
                    apiInfoList.add(buildApiInfo(path, "POST", pathItem.getPost(), openAPI.getInfo().getTitle()));
                }
                // 同理可添加PUT、DELETE等方法的解析...
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return apiInfoList;
    }

    /**
     * 构建单个接口的ApiInfo对象
     */
    private static ApiInfo buildApiInfo(String path, String method, Operation operation, String serviceName) {
        ApiInfo apiInfo = new ApiInfo();
        apiInfo.setPath(path);
        apiInfo.setMethod(method);
        apiInfo.setServiceName(serviceName);
        apiInfo.setDescription(operation.getDescription());

        // 提取请求参数（转为JSON字符串）
        StringBuilder paramsBuilder = new StringBuilder("[");
        for (Parameter param : operation.getParameters()) {
            paramsBuilder.append("{")
                    .append("\"name\":\"").append(param.getName()).append("\",")
                    .append("\"type\":\"").append(param.getSchema().getType()).append("\",")
                    .append("\"required\":").append(param.getRequired())
                    .append("},");
        }
        if (paramsBuilder.length() > 1) {
            paramsBuilder.setLength(paramsBuilder.length() - 1);
        }
        paramsBuilder.append("]");
        apiInfo.setRequestParams(paramsBuilder.toString());

        // 提取响应结构（简化示例，实际可解析operation.getResponses()）
        apiInfo.setResponseSchema("{\"code\":0,\"data\":{},\"msg\":\"成功\"}");
        return apiInfo;
    }
}
